(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.account.createContinueController', createContinueController);
	createContinueController.$inject = ['$q', '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'accountService' ];
	function createContinueController($q, $scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, accountService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {}, datas = [], datasTwo = [];
		ctrl.layoutConfig = layoutConfig;
		var layout1=ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoPrefix.patternOptions;
		var layout2=ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoSuffix.patternOptions;
		ctrl.validatorConfig = validatorConfig;
		ctrl.account = {};
		ctrl.account.acctCcyList = ctrl.account.acctCcyList || [];
		initAcctCcyEdit();
		ctrl.isShowAcctCcyList = function(){
			if(ctrl.account.custAcctFlag == 'Y'){
				return false;
			}else{
				return true;
			}
		};
		
		ctrl.setPatternNames = function() {
			if(ctrl.judge =="Y"){
				if (ctrl.account.acctPatternFlag == "N") {
					delete ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoPrefix.patternOptions;
					delete ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoSuffix.patternOptions;
				} else {
					ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoPrefix.patternOptions = layout1;
					ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoSuffix.patternOptions = layout2;
				}
				ctrl.judge="N";
			}else if(ctrl.judge =="N"){
				if (ctrl.account.acctPatternFlag == "N") {
					delete ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoPrefix.patternOptions;
					delete ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoSuffix.patternOptions;
					ctrl.account.acctNoPrefix = null;
					ctrl.account.acctNoSuffix = null;
					ctrl.acctChanged();
					ctrl.acctChangedTwo();
					
				} else {
					ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoPrefix.patternOptions = layout1;
					ctrl.layoutConfig.formConfigs.general.gridConfigs.acctNoSuffix.patternOptions = layout2;
					ctrl.account.acctNoPrefix = null;
					ctrl.account.acctNoSuffix = null;
					ctrl.acctChanged();
					ctrl.acctChangedTwo();
					
				}
			}
		};
		
		ctrl.acctChanged = function(){
			ctrl.accountPatterns = [];
			for(var j=0; j < datas.length; j++){
				ctrl.accountPatterns.push(datas[j]);
			}
			if(ctrl.accountPatterns.length > 0 && ctrl.account.acctNoPrefix != null){
				var m=[], count=[];
				 for(var i=0; i < ctrl.accountPatterns.length; i++){
					 count.push(i);
					 if(ctrl.account.acctNoPrefix.indexOf(ctrl.accountPatterns[i].value) != -1){
						m.push(i);
					 }
				 }
				if(m.length > 0){
					var purify = function(arr1,arr2){
					  var as = [];
					  var arr ="."+arr1.join(".")+".";
					    for(var k=0; k<arr2.length; k++){
					        arr.indexOf("."+arr2[k]+".") === -1 ? as.push(datas[k]) : 0; 
					    }  
					    return as;  
					};
					ctrl.accountPatterns = purify(m, count);
				} 
			}
		};
		
		ctrl.acctChangedTwo = function(){
			ctrl.accountPatternsTwo = [];
			for(var j=0; j < datasTwo.length; j++){
				ctrl.accountPatternsTwo.push(datasTwo[j]);
			}
			if(ctrl.accountPatternsTwo.length > 0 && ctrl.account.acctNoSuffix != null){
				var m=[], count=[];
				 for(var i=0; i < ctrl.accountPatternsTwo.length; i++){
					 count.push(i);
					 if(ctrl.account.acctNoSuffix.indexOf(ctrl.accountPatternsTwo[i].value) != -1){
						m.push(i);
					 }
				 }
				if(m.length > 0){
					var purify = function(arr1,arr2){
					  var as = [];
					  var arr ="."+ arr1.join(".")+".";
					    for(var k=0;k<arr2.length;k++){  
					        arr.indexOf("."+arr2[k]+".") === -1 ? as.push(datasTwo[k]) : 0;
					    }  
					    return as;  
					};
					ctrl.accountPatternsTwo = purify(m, count);
				} 
			}
		};
		
		ctrl.setSplitFlag = function (account){
			if (account.custAcctFlag == 'Y') {
				account.splitFlag = 'N';
			}
		};
		
		ctrl.viewPatternListLookup = function (){
			modalService.openCustomDialogs({
				'dialogsModule' : 'cda.acctPatternLookup'
			});
		};
		
		ctrl.subMoreDataLookup = function (obj){
			modalService.openCustomDialogs({
			   'title': 'title.account.moredata',
			   'dialogsModule' : 'cda.acctMoreDataLookup',
			   'params': obj,
			   'btnCallback' : {
					'ok' : function(resultList) {
						ctrl.setMoreData(obj, resultList);
					}
				}	
			});
		};
		
		ctrl.splitAccountLookup = function (){
			var params = {};
			params.splitAcct = ctrl.account.splitAcct ||[];
			params.patternflag = ctrl.account.patternflag;
			modalService.openCustomDialogs({
			   'title': 'title.account.splitacct.lookup',
			   'dialogsModule' : 'cda.splitAccountLookup',
			   'params':params,
			   'btnCallback' : {
					'ok' : function(resultList) {
						ctrl.account.splitAcct = resultList.splitAcct ;
						ctrl.account.patternflag = resultList.patternflag;
					}
				}	
			});
		}; 
		
		ctrl.moreDataLookup = function (){
			modalService.openCustomDialogs({
			   'title': 'title.account.moredata',
			   'dialogsModule' : 'cda.acctMoreDataLookup',
			   'params': ctrl.account,
			   'btnCallback' : {
					'ok' : function(resultList) {
						ctrl.setMoreData(ctrl.account, resultList);
					}
				}	
			});
		};
		
		
		function initAcctCcyEdit(){
			ctrl.addAcctCcy = function(row) {
				return $q(function(resolved, rejected){
					modalService.openCustomDialogs({
						'title': 'title.account.acctccy.create',
						'dialogsModule' : 'cda.account.accountCcyEdit',
						'params': {"acctCcyList" : ctrl.account.acctCcyList},
						'btnCallback' : {
							'ok' : function(acctCcyObj) {
								angular.merge(row, acctCcyObj);
								resolved();
							},
							'close' : function(){
								rejected();
							}
						}
					});
				});
			};
			
			ctrl.editAcctCcy = function(row) {
				modalService.openCustomDialogs({
				   'title': 'title.account.acctccy.edit',
				   'dialogsModule' : 'cda.account.accountCcyEdit',
				   'params': {acctCcy : row.entity, "acctCcyReadonly" : 'Y'},
				   'btnCallback' : {
						'ok' : function(acctCcyObj) {
							angular.forEach(ctrl.account.acctCcyList, function(param, index) {
								if (param.$$hashKey == row.entity.$$hashKey) {
									ctrl.account.acctCcyList.splice(index, 1, acctCcyObj);
								}
							});
						}
					}
				});
			};
			initAcctCcyView();
		};
		
		function initAcctCcyView(){
			ctrl.viewAcctCcy = function(row) {
				var acctCcyObjOld = getAcctCcyObjByCcy(row.entity.acctCcy);
				modalService.openCustomDialogs({
				   'title': 'title.account.acctccy.view',
				   'dialogsModule' : 'cda.account.accountCcyView',
				   'params': {acctCcy : row.entity, acctCcyOld : acctCcyObjOld},
				   'btnCallback' : {
					}
				});
			};
		};
		
		function getAcctCcyObjByCcy(acctCcy){
			var result = {};
			if(ctrl.accountOld && ctrl.accountOld.acctCcyList && ctrl.accountOld.acctCcyList.length > 0){
				angular.forEach(ctrl.accountOld.acctCcyList, function(data, index, array){
					if(data.acctCcy == acctCcy){
						result = data;
					}
				});
			}
			return result;
		}
		
		ctrl.setMoreData = function(obj, resultList){
			obj.moreData = getMoreData(resultList);
		};
		
		function getMoreData(resultList){
			var firstLine = "_PARAMS_=";
			var nameValuePairs = "";
			var endOfLine = "\r\n";
			angular.forEach(resultList, function(result, key){
				var pValue = result.parmValue;
				if(key != 0) {
					firstLine += ";";
					nameValuePairs += endOfLine;
				}
				firstLine += result.parmName;		
				nameValuePairs += (result.parmName + '=' + pValue);
			});
			return firstLine + endOfLine + nameValuePairs;
		}
		
		ctrl.init = function() {
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.acctCcyList.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.account.acctCcyList';
			authService.createContinue(params).then(function(response) {
				accountService.getPatternName().then(function(patternNames){
					datas = patternNames;
					datasTwo = patternNames;
				});
				accountService.initOptions().then(function(result){
					//Initialization data
					ctrl.custAcctFlagOptions = result.custAcctFlagOptions;
					ctrl.acctPatternFlagOptions = result.acctPatternFlagOptions;
					ctrl.splitFlagOptions = result.splitFlagOptions;
					ctrl.summaryFlag1Options = result.summaryFlag1Options;
					ctrl.summaryFlag2Options = result.summaryFlag2Options;
					ctrl.acctTypeOptions = result.acctTypeOptions;
					ctrl.partyTypeOptions = result.partyTypeOptions;
					ctrl.acctCcyOptions = result.acctCcyOptions;
					ctrl.acctNoOptions = result.acctNoOptions;
					ctrl.accountPatterns = result.accountPatterns;
					ctrl.accountPatternsTwo = result.accountPatternsTwo;
					
					if (response.data && response.data.model && response.data.task) {
						ctrl.account = response.data.model;
						ctrl.account.taskId = response.data.task.taskId;
						ctrl.account.acctCcyList = ctrl.account.acctCcyList || [];
						ctrl.judge ="Y";
					}
				});
			});
		};
	
		ctrl.createContinueSave = function() {
			return authService.createContinueSave(ctrl.account).then(saveSuccessful, saveFailed);
		};

		ctrl.createContinueSubmit = function() {
			return authService.createContinueSubmit(ctrl.account).then(submitSuccessful, submitFailed);
		};

		ctrl.createContinueCancel = function() {
			modalService.openConfirmDialogs({
				'messages' : [ {msg : 'title.dialog.confirm.cancel', args : [ctrl.account.primaryKey]} ],
				'btnCallback' : {
					'ok' : function() {
						authService.createContinueCancel(ctrl.account).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedParamList = selectedRows;
		}

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.workflow.wfSetup.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.account.list',
					'state' : 'cda.account.list',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data && response.data.model) {
				ctrl.account = response.data.model;
			}
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}
		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.cancel' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.workflow.wfSetup.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.account.list',
					'state' : 'cda.account.list',
					'params' : {}
				}]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);
